
$( document ).ready(function() {
	if(sessionAuth!="true")
	{
		$('#emaildiv').html("<input type='text' placeholder='e-mail' id='username'>");
		$('#username').bind("change paste keyup", function() {
			if($(this).val().match(".*[@].+")==null)
				$('.orderbutton').prop('disabled', true);
			else $('.orderbutton').prop('disabled', false);

		});
	}
	$('#map-canvas').css('height', $('#search-part').height());
	$('#result-wrapper').hide();
	$('#right-preloader').hide();
	$('#promocode').hide();
});


function roundToTwo(num) {
	return +(Math.round(num + "e+2")  + "e-2");
}
function dateParse(date)
{
	var dateparts = date.split("/");
	var datestring = dateparts[2] + "-" + dateparts[0] + "-" +  dateparts[1];
	return datestring;

}
function setMarker(x, y, descr)
{
	var Latlng = new google.maps.LatLng(x, y);
	var mapOptions = {
		zoom: 15,
		center: Latlng,
		mapTypeId: google.maps.MapTypeId.HYBRID
	};
	map = new google.maps.Map(document.getElementById('map-canvas'),
			mapOptions);
	var marker = new google.maps.Marker({
		position: Latlng,
		map: map,
		title: descr
	});
	marker.setMap(map);
}

function orderButtonHandler()
{
	/*if ($('#username').val() != undefined && 
		$('#username').val().match(".*[@].+")==null)
	{
		$('.orderbutton').prop('disabled', true);
	}
	else 
	{*/
		$('.orderbutton').prop('disabled', false);
	/*}*/
}

function ShowResults()
{
	$('#results-count').empty();
	$('#result-table').hide();
	$('#pageNavPosition').hide();
	$('#result-wrapper').show();
	var result_body = $('#result_body');
	result_body.empty();
	res = JSON.parse(res);
	if(res.hasOwnProperty('Result'))
	{
		$('#result-table').show();
		$('#results-count').append(res.Result.length + " hotels found");
		$.each(res.Result, function (index, element)
		{
			var discountedPrice = roundToTwo(element.TotalPrice * (1 + (commission / 100.0) * (1 - (discount+promocodeDiscount) / 100.0)));
			var totalPrice = roundToTwo(element.TotalPrice * (1 + (commission / 100.0)));
			var neighbourhood = $.grep(res.MetaData.HotelMetaData.Neighborhoods, function (e)
			{
				return e.Id == element.NeighborhoodId;
			})[0];
			var rowstring;
			var latlong = neighbourhood.Centroid.split(',');
			var x = latlong[0];
			var y = latlong[1];
	  var displayedIndex = index+1;

			rowstring = "";
			rowstring += '<tr id='+displayedIndex.toString()+'>';
			rowstring += '<td>' + displayedIndex + '</td>';
			rowstring += '<td>' + neighbourhood.Name + '</td>';
			rowstring += '<td>' + element.CurrencyCode + " " + totalPrice + '</td>';
			rowstring += '<td>' + element.CurrencyCode + " " + discountedPrice + '</td>';
			rowstring += '<td>' + element.StarRating + '</td>';
			rowstring += '<td valign="middle">' + "<form method='post' action='Hotwire'>" +
							"<input type='hidden' name='adults' value=" + $('#adults').val() + ">" +
							"<input type='hidden' name='children' value=" + $('#children').val() + ">" +
							"<input type='hidden' name='action' value='makeOrder'> " +
							"<input type='hidden' name='hotelId' value='" + element.ResultId + "'>" +
							"<input type='hidden' name='username' value='" + $('#username').val() + "'>" +
							"<input type='hidden' name='promocode' value='" + "placeholder"+"'>" +
							"<input type='hidden' name='paymentMethod' value='" + $('#payment_method').val() + "'>" +

							"<input type='submit' class='orderbutton' value='Order'>" +
					"</form>"+'</td>';
			rowstring += '<td>' + "<input type='radio' name='to_show' onclick=\"setMarker("+x+", "+y+", '"+neighbourhood.Name.replace("'", "")+"')\">" + '</td>';



					rowstring += '</tr>';
			result_body.append(rowstring);
		});
 	pager = new Pager('result_body', 10, 'pager', 'pageNavPosition');
	pager.init();
	pager.showPage(1);
	
	$('#promocode').show();
		
	orderButtonHandler();

	}else
	{
		$('#results-count').append("no hotels found.");
		$('#promocode').hide();
	}
	$('#right-preloader').hide();
}

function makeOrder(hotel_id, username, promocode, payment_method){}

function MakeQuery()
{
	$('#right-preloader').show();
	$.post('Hotwire',
			{
				action: 'makeQuery',
				url: createHotwireURL()
			},
			function(data)
			{

				res = data;

				ShowResults();
			});
}
function createHotwireURL()
{
	var str1 = 'https://api.hotwire.com/v1/search/hotel?apikey=65w49vx9saqwuf2j66774ab3&format=jsonp';
	var deststr = "&dest="+document.getElementById("dest").value;
	var checkindate = "&startdate="+document.getElementById("checkin").value.toString();
	var checkoutdate = "&enddate="+document.getElementById("checkout").value.toString();
	var rooms = "&rooms="+document.getElementById("rooms").value.toString();
	var adults = "&adults="+document.getElementById("adults").value.toString();
	var children = "&children="+document.getElementById("children").value.toString();
	return str1+deststr+rooms+adults+children+checkindate+checkoutdate;

}

function CheckPromocode()
{
	//TODO: real check
	if($('#promocode').val() == "qqq")
	{
		$('#promocode').css('background-color', 'greenyellow');
		promocodeDiscount = 7;
		ShowResults();
	}
	else
	{
		$('#promocode').css('background-color', 'indianred');
	}
}

function parseDate(date)
{
	var arr = date.split('-');
	return arr[1]+'/'+arr[2]+'/'+arr[0];

}
var map;
function initialize() {
	var mapOptions = {
		zoom: 8,
		center: new google.maps.LatLng(50.5, 30.6),
		mapTypeId: google.maps.MapTypeId.HYBRID
	};
	map = new google.maps.Map(document.getElementById('map-canvas'),
			mapOptions);

}

google.maps.event.addDomListener(window, 'load', initialize);

$(document).ready(function() {
	$("#checkin").datepicker({
      //defaultDate: 0,
	  minDate: 0,
      onClose: function( selectedDate ) {
        $("#checkout").datepicker( "option", "minDate", selectedDate );
      }
    });
    $( "#checkout" ).datepicker({
      //defaultDate: 0,
	  minDate: 0,
      onClose: function( selectedDate ) {
        $( "#checkin" ).datepicker( "option", "maxDate", selectedDate );
      }
    });
	$('#checkin').datepicker("setDate", new Date());
    $('#checkout').datepicker("setDate", new Date());
});